<?php
class UsersController extends Controller
{
	public function init()
	{
		$this->view->app_url = 'autosave.php?s=';
		$this->view->contr_url = $this->view->app_url . $this->_dispatcher->_controller . '/';
		$this->view->action_url = $this->view->contr_url . $this->_dispatcher->_action;
	}
	
	public function regAction()
	{
		$t = '';
		
		if (isset($_POST['do']) && strcmp('add', $_POST['do']) === 0)
		{
			if (V::M('users')->autoSave())
				$this->redirect('', 'autosave.php?s=users/edit&t=' . urlencode('保存成功') . '&user_id=' . V::M('users')->getId(), 0);	
			else 
				$t = V::M('users')->getError();
				
			$this->view->user = $_REQUEST;
		}
		
		$this->view->user = $_REQUEST;
		$this->view->errors = V::M('users')->getErrors();
		$this->view->t = $t;
		$this->view->groups = V::getAdapter()->table('user_groups')->select();
	}
	
	public function editAction()
	{
		$user_id = isset($_POST['user_id']) ? (int) $_POST['user_id'] : 
						(isset($_GET['user_id']) ? (int) $_GET['user_id'] : 0);
		if ($user_id <= 0) 
			exit('用户ID不正确');
		
		if (isset($_POST['do']) && strcmp('edit', $_POST['do']) === 0)
		{
			if (empty($_REQUEST['user_password']))
				unset(V::M('users')->rules['user_password'], V::M('users')->rules['user_repassword'], $_REQUEST['user_password']);
			
			if (V::M('users')->autoSave($user_id))
				$_GET['t'] = '修改成功';
			else 
				$_GET['t'] = V::M('users')->getError();
		}
		
		$user = V::M('users')->load($user_id);
		$this->view->user = array_merge($_REQUEST, $user);
		
		$this->view->user_id = $user_id;
		$this->view->errors = V::M('users')->getErrors();
		$this->view->t = isset($_GET['t']) ? $_GET['t'] : '';
		$this->view->groups = V::getAdapter()->table('user_groups')->select();
	}
} 
